using System.Collections.Generic;
using Pagination.RangeCollector;

namespace Pagination.Storage
{
    public class ArrayBased : IStorage
    {
        private readonly List<int> elements;
        private readonly IRangeCollector rangeCollector;

        public ArrayBased(IRangeCollector rangeCollector)
        {
            this.rangeCollector = rangeCollector;
            elements = new List<int>();
        }

        #region IStorage Members

        public void Add(int element)
        {
            var index = elements.BinarySearch(element);
            if (index < 0)
                elements.Insert(~index, element);
            else
                elements.Insert(index, element);
        }

        public void Range(int from, int to)
        {
            for (var i = from - 1; i < to; ++i)
                rangeCollector.Append(elements[i]);
            rangeCollector.End();
        }

        #endregion
    }
}